﻿using Comm;
using GalaSoft.MvvmLight.Messaging;
using Kinlo.Model;
using Kinlo.Repo;
using Newtonsoft.Json;
using S7.Net;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Kinlo.UI.Main.Hepler;

namespace Kinlo.Core.Service
{
   public class CoreService
    {
        List<string> ReadBeforWeightNodes = new List<string>();
        List<string> ReadCodeNodes = new List<string>();
        List<string> ReadAfterWeightNodes = new List<string>();
        bool isDebug = false;
        System.Timers.Timer timer = new System.Timers.Timer(1000);
        System.Timers.Timer timer2 = new System.Timers.Timer(5000);
        System.Timers.Timer timer3 = new System.Timers.Timer(500);
        //自动导出记录定时器
         System.Timers.Timer timer4 = new System.Timers.Timer(1200000); 
        public static object Locker = new object();
        AfterWeightFirstRep AFDB = new AfterWeightFirstRep();
        BeforWeightFirstRep BFDB = new BeforWeightFirstRep();
        CodeFirstRep CFDB = new CodeFirstRep();
        CounterRep CNTDB = new CounterRep();
        bool IsDelete = false;
        Plc plc;
        public Boolean MESLoadingUsed = false;
        List<CodeFirst> CodeFirsts = new List<CodeFirst>();
        List<BeforWeightFirst> BeforWeightFirsts = new List<BeforWeightFirst>();
        List<AfterWeightFirst> AfterWeightFirsts = new List<AfterWeightFirst>();
        public int InCount = 0;
        public int OutCount = 0;
        public int OKCount = 0;
        public int NGCount = 0;
        public int DBNo = 11;
        public int DBNo2 = 11;
        public int ClearRecordDay = 60;
        UInt16 r0 = 0;
        UInt16 r1 = 1;
        UInt16 r2 = 2;

        string StrRegex = "";
        bool IsCheckBarcode = false;
        string ExportPath = @"..\ExportData";

        public CoreService(CountNing countNing)
        {
            try
            {
                //IsConnected = false;          
                bool.TryParse(ConfigurationManager.AppSettings["IsDelete"], out IsDelete); 
                timer.Elapsed += Timer_Elapsed; 
                 
                bool.TryParse(ConfigurationManager.AppSettings["IsDebug"], out isDebug);
                var ipaddr = "192.168.10.100";
                ipaddr = ConfigurationManager.AppSettings["Ipaddr"];
                int.TryParse(ConfigurationManager.AppSettings["DBNo"], out DBNo);
                int.TryParse(ConfigurationManager.AppSettings["DBNo2"], out DBNo2);
                plc = new Plc(CpuType.S71500, ipaddr, 0, 0); 

                var cnt = CNTDB.GetCounter(); 
                if (cnt != null)
                { 
                    InCount = cnt.InCount;
                    OutCount = cnt.OutCount;
                    OKCount = cnt.OKCount;
                    NGCount = cnt.NGCount;

                    Messenger.Default.Send<int>(InCount, "SendINCount");
                    Messenger.Default.Send<int>(OutCount, "SendOutCount");
                    Messenger.Default.Send<int>(OKCount, "SendOKCount");
                    Messenger.Default.Send<int>(NGCount, "SendNGCount"); 
                } else
                {
                    Log("counter 失败");
                }
                var regex = ConfigurationManager.AppSettings["Regex"];
                if (string.IsNullOrEmpty(regex))
                {
                    regex = "^[0-9a-zA-Z]$";
                }
                StrRegex = regex;
                var isCheckBarcode = ConfigurationManager.AppSettings["IsCheckBarcode"];
                if (string.IsNullOrEmpty(isCheckBarcode))
                {
                    IsCheckBarcode = false;
                }
                else
                {
                    bool.TryParse(isCheckBarcode, out IsCheckBarcode);
                }
                var exportPath = ConfigurationManager.AppSettings["ExportPath"];
                if (!string.IsNullOrEmpty(exportPath))
                {
                    ExportPath = exportPath;
                }

                var BatchNo = ConfigurationManager.AppSettings["BatchNo"];
                if (!string.IsNullOrEmpty(BatchNo))
                {
                    GlobalValues.BatchNo = BatchNo;
                }

                var clearRecordDay = ConfigurationManager.AppSettings["ClearRecordDay"];
                if (!string.IsNullOrEmpty(clearRecordDay))
                {
                    var day = 0;
                   if( int.TryParse(clearRecordDay, out day))
                    {
                        ClearRecordDay = day;
                    } 
                }

                

                timer2.Elapsed += Timer2_Elapsed;
                timer2.Enabled = true;
                timer4.Elapsed += Timer4_Elapsed;
                timer4.Enabled = true;
                Task.Run(() =>
                {
                    Timer4_Elapsed(null, null);
                });

                Messenger.Default.Register<int>(this, "SendToPlcClear",new Action<int>((s)=> SendToPLCClearSig()));

                //var weight = new AfterWeightFirst
                //{
                //    ID = Guid.NewGuid(),
                //    Index = 1,
                //    BeforWeight_One = 1.0f,
                //    AfterWeight_One = 1.0f,
                //    InjectionNum_One = 1.0f,
                //    InjectionNum_Offset_One = 1.0f,
                //    Result_One = 1.0f.ToString(),
                //    IsValidate = true,
                //    ProductDate = DateTime.Now,
                //    TrayNum = 1,
                //    TrayNo = 2,
                //    TrayCol = AfterWeight_Index,
                //    TrayIndex = 1,
                //    Code = "AASF",
                //    BatchNo = GlobalValues.BatchNo,
                //    RangeOfInjection_One = string.Format("{0}~{1}",
                //                   GlobalValues.InjStd - GlobalValues.InjOffset, GlobalValues.InjStd + GlobalValues.InjOffset)
                //};
                //AFDB.Add2(weight);


            }
            catch (Exception ex)
            {
                Log(string.Format("精朗称重软件 {0}", ex.Message));
            } 
        }
        void ClearRecordDays(int day)
        {
            try
            {

            }catch(Exception ex)
            {

            }
        }

        object Exportlocker = new object();
        private void Timer4_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            #region 1
            //try
            //{
            //    var dates=AFDB.GetUnExportDates();
            //    if(dates!=null&& dates.Count>0)
            //    {
            //        foreach(var date in dates)
            //        {
            //            try
            //            {
            //              var weights=  AFDB.GetAfterFirst(date.Date.ToString("yyyy-MM-dd"));
            //                if(weights!=null&&weights.Count>0)
            //                {
            //                    var sb = new StringBuilder();
            //                    sb.AppendFormat("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12}\n", 
            //                        "条码", "称号", "站号", "托盘号", "列号", "行号", "前重", "后重", "注液量", "偏差值", "结果", "生产日期", "批次号");                                 
            //                    foreach(var w in weights)
            //                    {
            //                        sb.AppendFormat("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12}\n",
            //                           w.Code,w.Index,w.TrayNum, w.TrayNo, w.TrayIndex,w.TrayCol,w.BeforWeight_One,w.AfterWeight_One,w.InjectionNum_One,
            //                           w.InjectionNum_Offset_One,w.Result_One,w.ProductDate,w.BatchNo);  
            //                    }

            //                    DateTime saveDate;
            //                    DateTime.TryParse(date.Date.ToString(), out saveDate);
            //                    var basePath = Path.Combine(ExportPath, saveDate.Year.ToString(), saveDate.Month.ToString()); 
            //                    if (!Directory.Exists(basePath))
            //                    {
            //                        Directory.CreateDirectory(basePath);
            //                    }
            //                    var fileName = Path.Combine(basePath, date.Date.ToString("yyyy-MM-dd") + ".CSV");
            //                    var fullName=Path.GetFullPath(fileName);
            //                    File.WriteAllText(fullName, sb.ToString(),Encoding.UTF8);  
            //                    Log(string.Format("{0} 导出保存成功", fullName));
            //                    AFDB.UpdateExportDataStatus(date.Date.ToString("yyyy-MM-dd"));
            //                }
            //            }
            //            catch(Exception ex)
            //            {
            //                Log(string.Format("导出文件{0}.CSV异常:{1}",date.Date, ex));
            //            } 
            //        }
            //    }
            //}
            //catch(Exception ex)
            //{
            //    Log(string.Format("导出文件异常:{0}", ex));
            //}

            #endregion

            if(Monitor.TryEnter(Exportlocker))
            {
                DateTime startTime = DateTime.Now, endTime = DateTime.Now;
                try
                {
                    try
                    { 
                        if (DateTime.Now.Hour > 8)
                        {
                           var days= AFDB.GetAfterFirstUnExportDate();
                            if (days != null && days.Count > 0)
                            {
                                foreach(var day in days)
                                {
                                    DateTime datetime;
                                    if (DateTime.TryParse(day, out datetime))
                                    {
                                       // Export(datetime.AddDays(1));
                                        Export(datetime);
                                    }
                                    else
                                    {
                                        Log(string.Format("导出日期格式错误{0}", day));
                                    }
                                }
                            }                        
                        }
                    }
                    catch (Exception ex)
                    {
                        Log(string.Format("导出文件异常 {0}",ex.Message));
                    }
                }
                catch (Exception ex)
                {
                    Log(string.Format("导出文件异常:{0}", ex.Message));
                }
                finally
                {
                    Monitor.Exit(Exportlocker);
                }
            } 

        }
        public void Export(DateTime datetime)
        {
            DateTime startTime = DateTime.Now, endTime = DateTime.Now;
            string fileName = "";
            try
            {
                try
                {
                    // var time1 = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd"));
                    var time1 = datetime;
                    startTime = time1.AddHours(-16);
                    endTime = time1.AddHours(8).AddSeconds(-1);
                    var weights = AFDB.GetAfterFirstByTime(startTime, endTime);

                    if (weights != null && weights.Count > 0)
                    {
                        var sb = new StringBuilder();
                        sb.AppendFormat("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14} \n",
                            "条码", "称号", "站号", "托盘号", "列号", "行号", "前重", "后重", "注液量", "偏差值", "测漏结果", "前称结果", "结果", "生产日期", "批次号");
                        var i = 0;
                        foreach (var w in weights)
                        {
                            sb.AppendFormat("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14}\n",
                               w.Code, w.Index, w.TrayNum, w.TrayNo, w.TrayIndex, w.TrayCol, w.BeforWeight_One, w.AfterWeight_One, w.InjectionNum_One,
                               w.InjectionNum_Offset_One, w.Vacaumm_Test_ok, w.BeforeWeight_ok, w.Result_One, w.ProductDate, w.BatchNo);
                        }

                        DateTime saveDate;
                        DateTime.TryParse(endTime.Date.ToString(), out saveDate);
                        var basePath = Path.Combine(ExportPath, saveDate.Year.ToString(), saveDate.Month.ToString());
                        if (!Directory.Exists(basePath))
                        {
                            Directory.CreateDirectory(basePath);
                        }
                        var index = 0;
                        fileName = Path.Combine(basePath, startTime.ToString("yyyy年MM月dd日HH时mm分ss秒") + "-" + endTime.ToString("yyyy年MM月dd日HH时mm分ss秒") + ".CSV");
                        var fullName = Path.GetFullPath(fileName);
                        while (File.Exists(fullName))
                        {
                            index++;
                            fileName = Path.Combine(basePath, startTime.ToString("yyyy年MM月dd日HH时mm分ss秒") + "-" + endTime.ToString("yyyy年MM月dd日HH时mm分ss秒") + "(" + index + ")" + ".CSV");
                            fullName = Path.GetFullPath(fileName);
                        }
                        File.WriteAllText(fullName, sb.ToString(), Encoding.UTF8);
                        Log(string.Format("{0} 导出保存成功", fileName));
                        var updateCount = AFDB.UpdateExportDataStatus(startTime, endTime);
                        Log(string.Format("更新了{0}条导出记录", updateCount));
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    Log(string.Format("导出文件{0}异常:{1}", fileName, ex));
                }
            }
            catch (Exception ex)
            {
                Log(string.Format("导出文件异常:{0}", ex.Message));
            }
        }

        private void Timer2_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                DatabaseStatus = CNTDB.GetDatabaseStatus();
               // Messenger.Default.Send<bool>(IsConnected, "SendPLCStatus"); 
            }
            catch(Exception ex)
            {}
        }

        #region new

        System.Timers.Timer KeepAlive = new System.Timers.Timer(2000); 

        bool isConnected;
        public bool IsConnected
        {
            get { return isConnected; }
            set
            {
                if (isConnected != value)
                {
                    isConnected = value;
                    Messenger.Default.Send<bool>(value, "SendPLCStatus");
                    Log(string.Format("连接{0}", value ? "成功" : "失败"));
                }
            }
        }
        bool databaseStatus;
        public bool DatabaseStatus
        {
            get { return databaseStatus; }
            set
            {
                if (databaseStatus != value)
                {
                    databaseStatus = value;
                    Messenger.Default.Send<bool>(databaseStatus, "SendDatabaseStatus");
                    Log(string.Format("数据库连接{0}", value ? "成功" : "失败"));
                }
            }
        }

        object locker1 = new object();
        Task createTask;
        Task runTask;
        Task run1;

        private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (run1 == null || run1.IsCompleted)
            {
                run1 = CreateRun1();
            }
        }

        public bool Open(Plc plc)
        {
            try
            {
                plc.Open();
                IsConnected = true;
                Log(string.Format("{0}连接成功", plc.IP));
                return true;

            }
            catch (Exception ex)
            {
                Log(string.Format("{0}连接失败 {1}", plc.IP, ex.Message));
                IsConnected = false;
                return false;
            }
        }

        bool Task1Run = true;
        public Task CreateRun1()
        {
            return Task.Run(() => {
                while (Task1Run)
                {
                    try
                    {
                        if (plc.IsConnected)
                        {
                            //IsConnected = true;
                            short[] cmds1 = new short[4]; 
                            var t = new T();
                            lock (Locker)
                            {
                                cmds1 = plc.Read(DataType.DataBlock, DBNo, 416, VarType.Int, 7) as short[];
                                var cmd2 = plc.Read(DataType.DataBlock, DBNo, 432, VarType.Real, 2) as float[];
                                var cmd3 = plc.Read(DataType.DataBlock, DBNo, 440, VarType.Int, 1);
                                var cmd4 = plc.Read(DataType.DataBlock, DBNo2, 0, VarType.Word, 2) as UInt16[];  
                               TrayNo = (Int16)cmd3; 
                                GlobalValues.InjStd = cmd2[0];
                                GlobalValues.InjOffset = cmd2[1];
                                GlobalValues.ClassTeam = cmd4[0].ToString();
                                GlobalValues.Classes = cmd4[1].ToString();

                                plc.Write(DataType.DataBlock, DBNo, 430, r1);
                            } 
                            if (cmds1 != null && cmds1.Length >= 7)
                            {
                                AfterWeight_TrayNum = cmds1[0];
                                AfterWeight_Index = cmds1[1];
                                TANK_NUM= cmds1[2];
                                //ReadCode = cmds1[3];
                                BeforWeight = cmds1[4];
                                AfterWeight = cmds1[5];
                                //Supplement = cmds1[6];                                 
                            }
                        }
                        else
                        {
                            IsConnected = false;
                            Log(string.Format("{0}通信失败", plc.IP));
                            Open(plc);
                        }
                        Thread.Sleep(100);
                    }
                    catch (Exception ex)
                    {
                        IsConnected = false;
                        Log(string.Format("{0}通信失败", plc.IP, ex.Message));
                    }
                }
            });
        }
         
        #endregion
        public int AfterWeight_TrayNum { get; set; }
        public int AfterWeight_Index { get; set; }
        public int TANK_NUM { get; set; }
        public int TrayNo { get; set; }

        int readCodeLock = 0;
        public int ReadCode
        {
            set
            {
                if (value == 1)
                {
                    if (0 == Interlocked.Exchange(ref readCodeLock, 1))
                    {
                        Task.Run(() =>
                        {
                            Log("开始前扫码");
                            ReadCodeHandle();

                        }).ContinueWith(t => Interlocked.Exchange(ref readCodeLock, 0));
                    }
                }
            }
        }
        int beforWeightLock = 0;
        public int BeforWeight
        {
            set
            {
                if (value == 1)
                {
                    if (0 == Interlocked.Exchange(ref beforWeightLock, 1))
                    {
                        Task.Run(() =>
                        {
                            Log("开始前称重");
                            BeforWeightHandle();

                        }).ContinueWith(t => Interlocked.Exchange(ref beforWeightLock, 0));
                    }
                }
            }
        }
        int afterWeighLock = 0;
        public int AfterWeight
        {
            set
            {
                if (value == 1)
                {
                    if (0 == Interlocked.Exchange(ref afterWeighLock, 1))
                    {
                        Task.Run(() =>
                        {
                            Log("开始后称重");
                            AfterWeightHandle();
                        }).ContinueWith(t => Interlocked.Exchange(ref afterWeighLock, 0));
                    }
                }
            }
        }
        int supplementLock = 0;
        public int Supplement
        {
            set
            {
                if (value == 1)
                {
                    if (0 == Interlocked.Exchange(ref supplementLock, 1))
                    {
                        Task.Run(() =>
                        {

                        }).ContinueWith(t => Interlocked.Exchange(ref supplementLock, 0));
                    }
                }
            }
        }

        int readCodeBase = 46;
        int classLen = 52;
        public void ReadCodeHandle()
        {
            try
            {
                if (IsConnected)
                {
                    var ts = new List<T1>();
                    lock (Locker)
                    {
                        for (var i = 0; i < 1; i++)
                        {
                            var t1 = new T1();
                            var nodeId = i * classLen + readCodeBase;
                            var len = plc.ReadClass(t1, DBNo, nodeId);
                            ts.Add(t1);
                        }
                    }
                    var count = 0;
                    if (ts.Count > 0)
                    {
                        var datetime = DateTime.Now;
                        for (var i = 0; i < ts.Count; i++)
                        {
                            var t1 = ts[i];
                            var fixt1 = t1.ConvertToFixT1();
                            if (fixt1.HaveBattry)
                            {
                                if (IsCheckBarcode)
                                {
                                    if (!Regex.IsMatch(fixt1.Code, StrRegex))
                                    {
                                        Log(string.Format("前扫码 {0} 不符合条码过滤规则,将忽略", fixt1.Code));
                                        continue;
                                    }
                                }

                                var weight = new CodeFirst
                                {
                                    ID=Guid.NewGuid(),
                                    Code = fixt1.Code,
                                    ProductDate = datetime,
                                    IsValidate = true
                                };
                                if (IsDelete)
                                {
                                    var r = CFDB.DeleteCodeFirst(weight);
                                    if (r > 0)
                                    {
                                        Log(string.Format("前扫码删除重复条码:{0}", weight.Code));
                                    }
                                }
                                var result = CFDB.Add2(weight);
                                if (result > 0)
                                {
                                    Interlocked.Increment(ref InCount);
                                    count++;
                                    Messenger.Default.Send<CodeFirst>(weight, "SendCodeFirst");
                                }
                            }
                        }
                        Log(string.Format("前扫码 共{0}条记录保存", count)); 
                        CNTDB.UpdateFrontCounter(InCount);
                       Messenger.Default.Send<int>(InCount, "SendINCount");

                    }
                    lock (Locker)
                    {
                        plc.Write(DataType.DataBlock, DBNo, 0, r0);
                    }
                }
            }
            catch (Exception ex)
            {
                IsConnected = false;
                Log(string.Format("{0} {1}", "ReadCodeHandle", ex.Message));
            }
        }

        int readBeforWeightBase = 0;
        int beforLen = 6;
        public void BeforWeightHandle()
        {
            try
            {
                if (IsConnected)
                {
                    var ts = new List<T2>();
                    lock (Locker)
                    {
                        for (var i = 0; i < 16; i++)
                        { 
                            var t = new T2();
                            var nodeId = i * beforLen + readBeforWeightBase;
                            var len = plc.ReadClass(t, DBNo, nodeId);
                            ts.Add(t);
                        }
                    }
                    var count = 0;
                    if (ts.Count > 0)
                    {
                        var datetime = DateTime.Now;
                        var weights = new List<BeforWeightFirst>();
                        for (var i = 0; i < ts.Count; i++)
                        {
                            var fixt1 = ts[i];
                           // var fixt1 = t1.ConvertToFixT1();

                            if (fixt1.HaveBattry)
                            {
                                var weight = new BeforWeightFirst
                                {
                                    ID = Guid.NewGuid(),
                                    Index = i + 1,
                                    //Weight_OK = fixt1.Weight_OK,
                                    BeforWeight_First = fixt1.BeforWeight,
                                    Code="",
                                    //Code = fixt1.Code,
                                    IsValidate = true,
                                    ProductDate = datetime,
                                    PoleEarOK=fixt1.PoleEarOK
                                };
                                if (IsDelete)
                                {
                                    var r = BFDB.DeleteBeforWeight(weight);
                                    if (r > 0)
                                    {
                                        Log(string.Format("前称重删除重复条码:{0}", weight.Code));
                                    }
                                }

                                var result = BFDB.Add2(weight);
                                if (result > 0)
                                {
                                    weights.Add(weight);
                                    Interlocked.Increment(ref InCount);
                                    count++;
                                }
                                CNTDB.UpdateFrontCounter(InCount);
                                Messenger.Default.Send<int>(InCount, "SendINCount");
                            }
                        }

                        Task.Run(() => { 
                            Messenger.Default.Send<List<BeforWeightFirst>>(weights, "SendBeforWeightFirst");
                        });

                       

                        Log(string.Format("前称重 共{0}条记录保存", count));

                    }
                    lock (Locker)
                    {
                        plc.Write(DataType.DataBlock, DBNo, 424, r0);
                    }
                }
            }
            catch (Exception ex)
            {
                IsConnected = false;
                Log(string.Format("{0} {1}", "BeforWeightHandle", ex.Message));
            }
        }

        int colsBase = 1746;
        int valsBase = 96;
        int colCount = 14;
        int afterLen = 20;
        public void AfterWeightHandle()
        {
            try
            { 
                if (IsConnected)
                { 
                    short[] cols = null;
                    var vals = new List<T1>();
                    lock (Locker)
                    { 
                        //cols = plc.Read(DataType.DataBlock, DBNo, colsBase, VarType.Int, colCount) as short[];
                        for (var i = 0; i < 16; i++)
                        {
                            var t = new T1();
                            var nodeId = i * afterLen + valsBase;
                            plc.ReadClass(t, DBNo, nodeId);
                            vals.Add(t);
                        }
                    }
                     
                    if (vals != null && vals.Count > 0)
                    {
                        var count = 0;  
                        var datetime = DateTime.Now;
                        var weights = new List<AfterWeightFirst>();
                        for (int i = 0; i < vals.Count; i++)
                        { 
                            var t = vals[i];    
                            if (t.HaveBattry)
                            {
                                var class1 = GlobalValues.ClassTeam == "1" ? "A班" : GlobalValues.ClassTeam == "1" ? "B班" : "C班";
                                var class2 = GlobalValues.Classes == "1" ? "白班" : "夜班";
                                // int col = cols[i + 2];
                                var weight = new AfterWeightFirst
                                {
                                    ID = Guid.NewGuid(),
                                    Index = i + 1,
                                    Vacaumm_Test_ok = t.Vacaumm_Test_ok,
                                    BeforeWeight_ok = t.BeforeWeight_ok,
                                    BeforWeight_One = t.BeforWeight,
                                    AfterWeight_One = t.AfterWeight,
                                    InjectionNum_One = t.Weight,
                                    InjectionNum_Offset_One = t.Offset,
                                    Result_One = t.Weight_OK.ToString(),
                                    IsValidate = true,
                                    ProductDate = datetime,
                                    TrayNum = TANK_NUM,
                                    TrayNo = TrayNo,
                                    TrayCol = AfterWeight_Index,
                                    TrayIndex = i + 1,
                                    Code = "",
                                    BatchNo = GlobalValues.BatchNo,
                                    BillNo = GlobalValues.BillNo,
                                    ClassTeam = class1,
                                    Classes = class2,
                                    RangeOfInjection_One = string.Format("{0}~{1}", GlobalValues.InjStd - GlobalValues.InjOffset, GlobalValues.InjStd + GlobalValues.InjOffset),
                                    EquNo = GlobalValues.DeviceNo,
                                    EmpNo = GlobalValues.UserNo
                                }; 
                                if (t.Weight_OK)
                                {
                                    Interlocked.Increment(ref OKCount);
                                }
                                else
                                {
                                    Interlocked.Increment(ref NGCount);
                                }
                                
                                var result = AFDB.Add2(weight); 

                                if (result > 0)
                                {
                                    weights.Add(weight);

                                    Interlocked.Increment(ref OutCount);
                                    count++;
                                } 
                            }
                        } 
                        Task.Run(() => {
                            Messenger.Default.Send<List<AfterWeightFirst>>(weights, "SendAfterWeightFirst");
                        });
                         
                        Log(string.Format("后称重 共{0}条记录保存", count));
                        CNTDB.UpdateBackCounter(OutCount, OKCount, NGCount);

                        Messenger.Default.Send<int>(OutCount, "SendOutCount");
                        Messenger.Default.Send<int>(OKCount, "SendOKCount");
                        Messenger.Default.Send<int>(NGCount, "SendNGCount"); 
                    } 
                    lock (Locker)
                    {
                        plc.Write(DataType.DataBlock, DBNo, 426, r0);
                    } 
                }
            }
            catch (Exception ex)
            {
                IsConnected = false;
                Log(string.Format("{0} {1}", "AfterWeightHandle", ex.Message));
            }
        } 
        public void SendToPLCClearSig()
        {
            try
            {
                lock (Locker)
                {
                    plc.Write(DataType.DataBlock, DBNo, 2614, r1);
                    Log(string.Format("向PLC发送计数清零命令"));
                }
            }
            catch(Exception ex)
            {
                Log(string.Format("向PLC发送计数清零命令异常:{0}", ex));
            }
        }

        public void Start()
        {
            Log("开始");
            timer.Enabled = true;
            //timer3.Enabled = true;
            //数据刷新
            //timer2.Enabled = true;
        }
        public void Stop()
        {
            Log("停止");
            timer.Enabled = false;
            //timer2.Enabled = false;
        }
        public void Log(string msg)
        {
            Messenger.Default.Send<string>(msg, "ReceiveEventInfo");
            Logger.Log.Info(msg);
        } 

    }
}
